import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

const routes = [{
  path: '/',
  redirect: '/home/index'
},
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '@/views/login')
  },
  {
    path: '/home',
    name: 'home',
    component: () => import(/* webpackChunkName: "home" */ '@/views/home'),
    children: [{
      path: '/home/index',
      name: 'index',
      component: () => import(/* webpackChunkName: "index" */ '@/views/home/index/index.vue'),
    },{
      path: '/home/classify',
      name: 'classify',
      component: () => import(/* webpackChunkName: "classify" */ '@/views/home/classify'),
    },{
      path: '/home/shop',
      name: 'shop',
      component: () => import(/* webpackChunkName: "shop" */ '@/views/home/shop'),
    },{
      path: '/home/my',
      name: 'my',
      component: () => import(/* webpackChunkName: "my" */ '@/views/home/my'),
    }]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 全局前置守卫

router.beforeEach((to, from, next) => {
  // to跳转的路由对象
  // from 离开的对象
  // next 钩子函数
  console.log(to);
  console.log(from);
  // 跳转的是购物车页面 并且 没有登录
  if(to.path === "/home/shop") {
    // 跳转到登录页面
    if(from.path === "/home/index") {
      if(localStorage.getItem('token')) {
        next()
      } else {
        next('/login')
      }
    } else {
      next(false)
    }  
  } else {
    // 正常跳转
    next()
  }

})

export default router
